import { defineStore } from 'pinia'
import { ElMessage } from 'element-plus'
import { enterpriseAPI, jobAPI, reviewAPI, employeeAPI, apiUtils } from '@/api/enterprise'

export const useEnterpriseStore = defineStore('enterprise', {
  state: () => ({
    // 企业信息
    enterpriseInfo: null,
    
    // 企业列表
    enterpriseList: [],
    
    // 岗位列表
    jobList: [],
    
    // 评价列表
    reviewList: [],
    
    // 员工列表
    employeeList: [],
    
    // 岗位统计数据
    jobStatistics: null,
    
    // 企业统计数据
    enterpriseStatistics: null,
    
    // 分页信息
    pagination: {
      enterprises: { total: 0, currentPage: 1, pageSize: 10 },
      jobs: { total: 0, currentPage: 1, pageSize: 10 },
      reviews: { total: 0, currentPage: 1, pageSize: 10 },
      employees: { total: 0, currentPage: 1, pageSize: 10 }
    },
    
    // 加载状态
    loading: {
      enterpriseInfo: false,
      enterpriseList: false,
      jobList: false,
      reviewList: false,
      employeeList: false,
      statistics: false
    }
  }),

  getters: {
    // 获取活跃岗位数量
    activeJobCount: (state) => {
      return state.jobList.filter(job => job.jobStatus === 'active').length
    },
    
    // 获取平均评分
    averageRating: (state) => {
      if (!state.reviewList.length) return 0
      const totalRating = state.reviewList.reduce((sum, review) => sum + review.rating, 0)
      return Math.round((totalRating / state.reviewList.length) * 100) / 100
    },
    
    // 获取企业状态文本
    enterpriseStatusText: (state) => {
      const statusMap = {
        active: '已认证',
        inactive: '未认证',
        pending: '待审核'
      }
      return statusMap[state.enterpriseInfo?.status] || '未知'
    },
    
    // 获取评价列表（与 reviewList 同步）
    reviews: (state) => {
      return state.reviewList
    },
    
    // 获取评价统计
    reviewStats: (state) => {
      const total = state.reviewList.length
      const distribution = {}
      
      // 计算评分分布
      for (let i = 1; i <= 5; i++) {
        distribution[i] = state.reviewList.filter(review => review.rating === i).length
      }
      
      return {
        total,
        distribution
      }
    }
  },

  actions: {
    // 获取企业信息
    async fetchEnterpriseInfo(enterpriseId) {
      this.loading.enterpriseInfo = true
      try {
        const response = await enterpriseAPI.getEnterpriseInfo(enterpriseId)
        this.enterpriseInfo = response.data
        // 不显示成功消息，避免在切换公司时频繁提示
        // ElMessage.success('企业信息获取成功')
        return response.data
      } catch (error) {
        const message = apiUtils.handleApiError(error)
        ElMessage.error(message)
        throw error
      } finally {
        this.loading.enterpriseInfo = false
      }
    },

    // 设置企业信息
    setEnterpriseInfo(enterpriseData) {
      this.enterpriseInfo = enterpriseData
    },

    // 更新企业信息
    async updateEnterpriseInfo(enterpriseId, updateData) {
      try {
        const response = await enterpriseAPI.updateEnterpriseInfo(enterpriseId, updateData)
        if (response.success) {
          // 更新本地状态
          if (this.enterpriseInfo && this.enterpriseInfo.enterpriseId === enterpriseId) {
            this.enterpriseInfo = { ...this.enterpriseInfo, ...updateData }
          }
          ElMessage.success('企业信息更新成功')
          return true
        }
      } catch (error) {
        const message = apiUtils.handleApiError(error)
        ElMessage.error(message)
        throw error
      }
    },

    // 获取企业列表
    async fetchEnterpriseList(params = {}) {
      this.loading.enterpriseList = true
      try {
        const response = await enterpriseAPI.getEnterpriseList(params)
        this.enterpriseList = response.data
        this.pagination.enterprises = response.pagination
        return response
      } catch (error) {
        const message = apiUtils.handleApiError(error)
        ElMessage.error(message)
        throw error
      } finally {
        this.loading.enterpriseList = false
      }
    },

    // 创建企业
    async createEnterprise(enterpriseData) {
      try {
        const response = await enterpriseAPI.createEnterprise(enterpriseData)
        if (response.success) {
          ElMessage.success('企业创建成功')
          return response.data
        }
      } catch (error) {
        const message = apiUtils.handleApiError(error)
        ElMessage.error(message)
        throw error
      }
    },

    // 删除企业
    async deleteEnterprise(enterpriseId) {
      try {
        const response = await enterpriseAPI.deleteEnterprise(enterpriseId)
        if (response.success) {
          // 从列表中移除
          this.enterpriseList = this.enterpriseList.filter(enterprise => 
            enterprise.enterpriseId !== enterpriseId
          )
          ElMessage.success('企业删除成功')
          return true
        }
      } catch (error) {
        const message = apiUtils.handleApiError(error)
        ElMessage.error(message)
        throw error
      }
    },

    // 获取企业岗位列表
    async fetchEnterpriseJobs(enterpriseId, params = {}) {
      this.loading.jobList = true
      try {
        const response = await jobAPI.getEnterpriseJobs(enterpriseId, params)
        this.jobList = response.data
        this.pagination.jobs = response.pagination
        return response
      } catch (error) {
        const message = apiUtils.handleApiError(error)
        ElMessage.error(message)
        throw error
      } finally {
        this.loading.jobList = false
      }
    },

    // 创建岗位
    async createJob(enterpriseId, jobData) {
      try {
        const response = await jobAPI.createJob(enterpriseId, jobData)
        if (response.success) {
          // 添加到列表中
          this.jobList.unshift(response.data)
          this.pagination.jobs.total++
          ElMessage.success('岗位创建成功')
          return response.data
        }
      } catch (error) {
        const message = apiUtils.handleApiError(error)
        ElMessage.error(message)
        throw error
      }
    },

    // 更新岗位
    async updateJob(jobId, updateData) {
      try {
        const response = await jobAPI.updateJob(jobId, updateData)
        if (response.success) {
          // 更新本地状态
          const index = this.jobList.findIndex(job => job.jobId === jobId)
          if (index !== -1) {
            this.jobList[index] = { ...this.jobList[index], ...updateData }
          }
          ElMessage.success('岗位更新成功')
          return true
        }
      } catch (error) {
        const message = apiUtils.handleApiError(error)
        ElMessage.error(message)
        throw error
      }
    },

    // 删除岗位
    async deleteJob(jobId) {
      try {
        const response = await jobAPI.deleteJob(jobId)
        if (response.success) {
          // 从列表中移除
          this.jobList = this.jobList.filter(job => job.jobId !== jobId)
          this.pagination.jobs.total--
          ElMessage.success('岗位删除成功')
          return true
        }
      } catch (error) {
        const message = apiUtils.handleApiError(error)
        ElMessage.error(message)
        throw error
      }
    },

    // 更新岗位状态
    async updateJobStatus(jobId, status) {
      try {
        const response = await jobAPI.updateJobStatus(jobId, status)
        if (response.success) {
          // 更新本地状态
          const job = this.jobList.find(j => j.jobId === jobId)
          if (job) {
            job.jobStatus = status
          }
          ElMessage.success('岗位状态更新成功')
          return true
        }
      } catch (error) {
        const message = apiUtils.handleApiError(error)
        ElMessage.error(message)
        throw error
      }
    },

    // 批量操作岗位
    async batchOperateJobs(jobIds, operation) {
      try {
        const response = await jobAPI.batchOperateJobs(jobIds, operation)
        if (response.success) {
          // 根据操作类型更新本地状态
          if (operation === 'delete') {
            this.jobList = this.jobList.filter(job => !jobIds.includes(job.jobId))
            this.pagination.jobs.total -= jobIds.length
          } else if (operation === 'pause' || operation === 'activate') {
            const status = operation === 'pause' ? 'inactive' : 'active'
            this.jobList.forEach(job => {
              if (jobIds.includes(job.jobId)) {
                job.jobStatus = status
              }
            })
          }
          ElMessage.success('批量操作成功')
          return response.data
        }
      } catch (error) {
        const message = apiUtils.handleApiError(error)
        ElMessage.error(message)
        throw error
      }
    },

    // 搜索岗位
    async searchJobs(params = {}) {
      this.loading.jobList = true
      try {
        const response = await jobAPI.searchJobs(params)
        this.jobList = response.data
        this.pagination.jobs = response.pagination
        return response
      } catch (error) {
        const message = apiUtils.handleApiError(error)
        ElMessage.error(message)
        throw error
      } finally {
        this.loading.jobList = false
      }
    },

    // 获取岗位详情
    async fetchJobDetail(jobId) {
      try {
        const response = await jobAPI.getJobDetail(jobId)
        return response.data
      } catch (error) {
        const message = apiUtils.handleApiError(error)
        ElMessage.error(message)
        throw error
      }
    },

    // 获取岗位统计数据
    async fetchJobStatistics(jobId) {
      this.loading.statistics = true
      try {
        const response = await jobAPI.getJobStatistics(jobId)
        this.jobStatistics = response.data
        return response.data
      } catch (error) {
        const message = apiUtils.handleApiError(error)
        ElMessage.error(message)
        throw error
      } finally {
        this.loading.statistics = false
      }
    },

    // 获取企业评价列表
    async fetchEnterpriseReviews(enterpriseId, params = {}) {
      this.loading.reviewList = true
      try {
        const response = await reviewAPI.getEnterpriseReviews(enterpriseId, params)
        this.reviewList = response.data
        this.pagination.reviews = response.pagination
        return response
      } catch (error) {
        const message = apiUtils.handleApiError(error)
        ElMessage.error(message)
        throw error
      } finally {
        this.loading.reviewList = false
      }
    },

    // 回复评价
    async replyReview(reviewId, replyContent) {
      try {
        const response = await reviewAPI.replyReview(reviewId, replyContent)
        if (response.success) {
          // 更新本地状态
          const review = this.reviewList.find(r => r.reviewId === reviewId)
          if (review) {
            review.replyContent = replyContent
            review.replyTime = new Date().toISOString()
          }
          ElMessage.success('回复成功')
          return true
        }
      } catch (error) {
        const message = apiUtils.handleApiError(error)
        ElMessage.error(message)
        throw error
      }
    },

    // 获取企业员工列表
    async fetchEnterpriseEmployees(enterpriseId, params = {}) {
      this.loading.employeeList = true
      try {
        const response = await employeeAPI.getEnterpriseEmployees(enterpriseId, params)
        this.employeeList = response.data
        this.pagination.employees = response.pagination
        return response
      } catch (error) {
        const message = apiUtils.handleApiError(error)
        ElMessage.error(message)
        throw error
      } finally {
        this.loading.employeeList = false
      }
    },

    // 获取企业统计数据
    async fetchEnterpriseStatistics(enterpriseId) {
      this.loading.statistics = true
      try {
        const response = await enterpriseAPI.getEnterpriseStatistics(enterpriseId)
        this.enterpriseStatistics = response.data
        return response.data
      } catch (error) {
        const message = apiUtils.handleApiError(error)
        ElMessage.error(message)
        throw error
      } finally {
        this.loading.statistics = false
      }
    },

    // 重置状态
    resetState() {
      this.enterpriseInfo = null
      this.enterpriseList = []
      this.jobList = []
      this.reviewList = []
      this.employeeList = []
      this.jobStatistics = null
      this.enterpriseStatistics = null
    }
  },

  persist: {
    enabled: true,
    strategies: [
      {
        key: 'enterprise',
        storage: localStorage,
        paths: ['enterpriseInfo', 'pagination']
      }
    ]
  }
})
